<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'button'")
              Button(v-if="hasFind" type="info" @click="searchFn") 查询

      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable")
        .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
          .table-title-lefttxt.pull-left
            |应收合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.should}}
            |元
            Divider(type="vertical")
            |应付合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.pay}}
            |元
            Divider(type="vertical")
            |差额合计
            span.text-error.pl-5.pr-5.font-weight {{tableComone.balance}}
            |元
          .pull-right.table-title-btns
            Button.mr-10(v-if="hasExport" type="info" @click="handleShowBatchImportModal") 导入
            Button.mr-10(v-if="hasExport" type="info" @click="exportCompanyBalanceDetail") 导出
        template(slot-scope="{ row, index }" slot="action")
          Button(type="text" size="small" @click="handleShowBalanceProcessModal(row)" :disabled="row.canPostRemarks === 0") 差额处理
        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )

    //- 差额处理弹窗
    BalanceProcessModal(ref="BalanceProcessModal" @query="searchFn")

    //- 批量导入弹窗
    BatchImportModal(ref="BatchImportModal" @query="searchFn")
</template>

<script>
import { EnumApi } from '@/api/Enum.api.js'
import { SocialSecurityPayableBillApi } from '@/api/SocialSecurityPayableBill.api.js'
import { BalanceApi } from '@/api/Balance.api.js'
import { CustomerDetailThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import BalanceProcessModal from './modal/balanceProcessModal.vue'
import BatchImportModal from './modal/batchImportModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  components: {
    BalanceProcessModal,
    BatchImportModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(CustomerDetailThead),
      tableData: [],
      formData: {
        insureNo: '',
        handleType: ''
      },
      formItem: [
        { type: 'input', label: '参保编号：', placeholder: '请输入参保编号', prop: 'insureNo', model: 'insureNo', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'select', label: '处理方式：', placeholder: '请选择处理方式', prop: 'handleType', model: 'handleType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8', options: 'balancehandle' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' }
      ],
      rules: {},
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        should: 0, // 应收合计
        pay: 0, // 应付合计
        balance: 0 // 差额合计
      },
      downLoadRul: '',
      arrListDown: {
        balancehandle: [{ value: 0, label: '未处理' }, { value: 1, label: '已处理' }]
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      queryResult: []
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    }
  },

  watch: {
  },

  mounted () {
    // this.getEnum()
    this.query()
  },

  methods: {
    // 数据字典
    // getEnum () {
    //   let groupName = 'balance.balancehandle'
    //   Common.getEnum(groupName, this.arrListDown)
    //   // console.log('数据字典：', this.arrListDown)
    // },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      // const month = this.$route.query.month < 10 ? '0' + this.$route.query.month : this.$route.query.month
      var params = {
        // HasPaging: true,
        // Year: this.$route.query.year,
        // Month: this.$route.query.month,
        CompanyName: this.$route.query.companyName,
        CompanyId: this.$route.query.companyId,
        FeeYearMonthStart: this.$route.query.year + '-' + this.$route.query.month,
        FeeYearMonthEnd: this.$route.query.year + '-' + this.$route.query.month,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        InsureNo: this.formData.insureNo,
        Status: this.formData.handleType
      }
      let res = await BalanceApi.getCompanyBalanceDetail(params)
      console.log('客户差额详情res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.queryResult = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.should = res.data.should
        this.tableComone.pay = res.data.pay
        this.tableComone.balance = res.data.balance
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 导出客户差额明细账单
    async exportCompanyBalanceDetail () {
      var params = {
        CompanyName: this.$route.query.companyName,
        CompanyId: this.$route.query.companyId,
        FeeYearMonthStart: this.$route.query.year + '-' + this.$route.query.month,
        FeeYearMonthEnd: this.$route.query.year + '-' + this.$route.query.month,
        InsureNo: this.formData.insureNo,
        status: this.formData.handleType
      }
      console.log('params: ', params)
      let res = await BalanceApi.exportCompanyBalanceDetail(params)
      console.log('导出客户差额明细账单res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 显示差额处理弹窗
    handleShowBalanceProcessModal (row) {
      console.log('row: ', row)
      this.$refs.BalanceProcessModal.isShowBalanceProcessModal = true
      this.$refs.BalanceProcessModal.currentRow = row
      localStorage.removeItem('tempAddBalanceArr')
      this.$refs.BalanceProcessModal.tableData = []
    },

    // 批量导入-显示弹窗
    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.actionUrl = '/api/Balance/ImportBalanceHandle'
      this.$refs.BatchImportModal.file = null
      this.$refs.BatchImportModal.errorData.isError = false
      this.$refs.BatchImportModal.show()
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
